#include "screenboxgrabber.h"

ScreenBoxGrabber::ScreenBoxGrabber() { m_dragging = false; }
ScreenBoxGrabber::~ScreenBoxGrabber() { removeFromMouseGrabberPool(); }

void
ScreenBoxGrabber::checkIfGrabsMouse(int x, int y,
				  const Camera* const camera)
{
  QPointF pos = position();
  float sx, sy;
  size(sx, sy);

  int scw = camera->screenWidth();
  int sch = camera->screenHeight();

  int cxs, cys, cxe, cye;
  cxs = (pos.x()-sx)*scw;  cys = (pos.y()-sy)*sch;
  cxe = (pos.x()+sx)*scw;  cye = (pos.y()+sy)*sch;

  if (m_dragging ||
      x >= cxs && x <= cxe &&
      y >= cys && y <= cye)
    setGrabsMouse(true);
  else
    setGrabsMouse(false);
}

void
ScreenBoxGrabber::mousePressEvent(QMouseEvent* const event,
				Camera* const camera)
{
  m_dragging = true;
  m_prevx = event->x();
  m_prevy = event->y();
  m_prevpos = position();
}
void
ScreenBoxGrabber::mouseReleaseEvent(QMouseEvent* const event,
				  Camera* const camera)
{
  m_dragging = false;
}
void
ScreenBoxGrabber::mouseMoveEvent(QMouseEvent* const event,
				Camera* const camera)
{
  if (m_dragging)
    {

      float dx = event->x()-m_prevx;
      float dy = event->y()-m_prevy;

      dx /= camera->screenWidth();
      dy /= camera->screenHeight();      
      setPosition(m_prevpos+QPointF(dx,dy));
    }
}

ScreenBoxObject
ScreenBoxGrabber::screenbox()
{
  ScreenBoxObject so;
  float x, y;
  size(x, y);
  so.set(position(), lod(), x, y);
  return so;
}
